package com.gdk.ksoft.assembly.utils;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.gdk.ksoft.data.common.ConstantData;
import com.gdk.ksoft.data.common.SystemData;
import com.gdk.ksoft.data.entry.datas.BaseResultModel;
import com.gdk.ksoft.assembly.dialog.MessageBox;
import com.gdk.ksoft.assembly.dialog.UpdateVersionDialog;
import com.gdk.ksoft.assembly.utils.extensions.MD5Utils;
import com.gdk.ksoft.assembly.utils.system.ApkUtils;
import com.gdk.ksoft.assembly.utils.system.NetworkUtils;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONObject;

/**
 * Created by hel on 2014-12-10.
 * 版本更新操作
 */
public class UpdateUtils {


    /**
     * 检测版本更新
     * @param context
     */
    public static void checkVersion(final Context context,final boolean isNeedNotice){
        if(!NetworkUtils.isNetAvailable(context)) return;//网络不可用
        String methodName = "Cx_BanBen";
        final int versionCode = ApkUtils.getVersionCode(context);//获取软件的版本值
        String messageBody = "{\"Sjch\":\"" + SystemData.PhoneIMEI + "\",\"Data\":{\"bbz\":\""+versionCode+"\"}}";
        RequestParams params = new RequestParams();
        params.addBodyParameter("Method", methodName);
        params.addBodyParameter("Digest", MD5Utils.getMd5(methodName + messageBody + "19491001"));
        params.addBodyParameter("MessageBody", messageBody);
        System.out.println("------>正在请求版本检测 |==>"+messageBody);
        new HttpUtils(ConstantData.NETWORK_CONNECT_TIME_OUT).configSoTimeout(ConstantData.NETWORK_READ_TIME_OUT)
                .send(HttpRequest.HttpMethod.POST, ConstantData.UPDATE_URL + "/Mobile/CheXiao/", params, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> objectResponseInfo) {
                        System.out.println("------>版本检测结果是：" + objectResponseInfo.result);
                        BaseResultModel resultModel = new Gson().fromJson(objectResponseInfo.result, BaseResultModel.class);
                        if (resultModel != null && resultModel.Result.equals("0000")) {
                            if (!TextUtils.isEmpty(resultModel.Data)) {
                                try {
                                    JSONArray jarr = new JSONArray(resultModel.Data.trim());
                                    if (jarr != null && jarr.length() > 0) {
                                        final JSONObject jsonObject = (JSONObject) jarr.get(0);
                                        if (jsonObject != null && jsonObject.getInt("bbz") != versionCode) {
                                            final MessageBox msgBox = new MessageBox(context);
                                            msgBox.setMessage("  检测到服务器新版本" + jsonObject.getString("bbms")
                                                    +"!请及时替换并安装更新，以防出现不必要的麻烦!");
                                            msgBox.onPositiveNegitiveClick(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    msgBox.dismiss();
                                                    try {
                                                        if (v.getId() == MessageBox.ID_DIALOG_BUTTON_OK && jsonObject.getString("wjdz") != null) {//确定按钮
                                                            UpdateVersionDialog dialog = new UpdateVersionDialog(context,
                                                                    ConstantData.UPDATE_URL + jsonObject.getString("wjdz").replaceAll("\\\\", "/"));
                                                            dialog.downloadApk();//下载更新
                                                            dialog.show();
                                                        }
                                                    } catch (Exception e) {
                                                        e.printStackTrace();
                                                        Toast.makeText(context, "下载更新异常!原因：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                                                    }
                                                }
                                            });
                                            msgBox.show();
                                        } else {
                                            showNotice(context, isNeedNotice, "已经是最新版本了!");
                                        }
                                    } else {
                                        showNotice(context, isNeedNotice, "已经是最新版本了!");
                                    }
                                } catch (Exception e) {
                                    showNotice(context, isNeedNotice, "已经是最新版本了!");
                                    e.printStackTrace();
                                }
                            }
                        } else {
                            showNotice(context, isNeedNotice, "检测版本更新失败!" + resultModel.Message);
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        System.out.println("------>版本检测结果: 失败,原因--->" + s);
                        showNotice(context, isNeedNotice, "检测版本更新失败!");
                    }
                });
    }

    /**
     * 显示提示
     * @param context
     * @param isNeedNotice
     * @param message
     */
    public static void showNotice(Context context,boolean isNeedNotice,String message){
        if(isNeedNotice){
            Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
        }
    }

}
